<template>
  <div class="viewContain">
    <el-row>
      <el-col :span="8">
        <el-card shadow="hover" :style="tree" class="tree">
          <el-tree
            ref="tree"
            v-loading="treeLoading"
            :props="defaultProps"
            :data="locationTreeDate"
            accordion
            highlight-current
            default-expand-all
            @current-change="CurrentNode"
          />
        </el-card>
      </el-col>
      <el-col v-loading="loading" :offset="4" :span="12">
        <section v-if="!isAdd" class="top-button">
          <el-button size="mini" type="primary" @click="addArea">新增</el-button>
          <el-button size="mini" type="primary" @click="updateArea">修改</el-button>
          <el-button size="mini" type="danger" @click="delArea">删除</el-button>
        </section>
        <section v-if="isAdd" class="top-button">
          <el-button size="mini" type="primary" @click="sureAdd">保存</el-button>
          <el-button size="mini" type="primary" plain @click="closeAdd">取消</el-button>
        </section>
        <section class="tree-right">
          <el-form ref="addRegionForm" :model="addRegionForm" label-width="120px" :rules="addRegionFormRules" size="small">
            <el-col v-if="!isAdd" :span="24">
              <el-form-item label="区域ID：" style="width: 100%">
                <el-input v-model="addRegionForm.distinctId" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="区域名称：" prop="name" style="width: 100%;">
                <el-input v-model="addRegionForm.name" auto-complete="off" placeholder="输入的需要增加区域名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="区域编码：" prop="code" style="width: 100%;">
                <el-input v-model="addRegionForm.code" auto-complete="off" placeholder="输入的需要增加区域编码" :disabled="areaCodeShow" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="父级名称：" style="width: 100%;">
                <el-input v-model="addRegionForm.parentName" auto-complete="off" placeholder="根节点" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-form>
        </section>
      </el-col>
    </el-row>
  </div>
</template>
<style scoped>

</style>
<script>
import { getRegionTreeByParentId, getRegionById, updateRegionById, insertRegionInfo, delRegionById } from '@a/core/region.js'
export default {
  data() {
    return {
      loading: false,
      isAdd: false,
      selOne: {},
      // oName: '',
      // oCode: '',
      tree: {
        height: window.innerHeight - 200 + 'px'
      },
      treeLoading: false,
      //  区域编码控制是否可读的变量:false是可读，true是不可读
      areaCodeShow: false,
      // 弹出窗口进行 属性校验
      addRegionFormRules: {
        name: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('区域名称不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        },
        code: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('区域编码不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      },
      // 新增界面数据
      addRegionForm: {
        distinctId: '',
        parentId: '',
        parentName: '',
        name: '',
        code: ''
      },
      locationTreeDate: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      regionId: '',
      oId: ''
    }
  },
  created() {
    this.regionId = JSON.parse(localStorage.getItem('userInfo')).areaId
    // this.regionTreeInit(this.regionId)
    this.regionTreeInit(0)
  },
  methods: {
    // 查询区域树形结构
    regionTreeInit(parentId) {
      this.treeLoading = true
      getRegionTreeByParentId(parentId).then(res => {
        // console.log(res)
        this.treeLoading = false
        if (res.data) {
          this.locationTreeDate = res.data
          const oData = res.data[0]
          this.CurrentNode(oData)
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }).catch(err => {
        this.treeLoading = false
        console.log(err)
      })
    },
    // 点击树节点方法
    CurrentNode(value) {
      console.log(value)
      const id = value.id
      if (!value.children) {
        this.treeLoading = true
        getRegionTreeByParentId(id).then(res => {
          // console.log(res)
          this.treeLoading = false
          if (res.data) {
            const newChild = res.data
            this.$set(value, 'children', newChild)
          }
        }).catch(err => {
          this.treeLoading = false
          console.log(err)
        })
      }
      // 获取界面内容
      this.loading = true
      if (id !== '') {
        this.getRegDetail(id)
      }
      this.oId = id
    },
    getRegDetail(id) {
      console.log(id)
      getRegionById(id).then(res => {
        // console.log(res)
        this.loading = false
        if (res.data) {
          this.addRegionForm = res.data
          this.selOne = res.data
        }
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    // 【修改】方法
    updateArea() {
      this.$refs.addRegionForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const para = Object.assign({}, this.addRegionForm)
          // 发送请求
          updateRegionById(para).then(res => {
            this.loading = false
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.regionTreeInit(0)
            } else if (res.code === -1) {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }
          }).catch(err => {
            this.loading = false
            console.log(err)
          })
        }
      })
    },
    // 重置界面内容
    resetForm(formName) {
      if (this.$refs[formName] === undefined) {
        return
      }
      this.$refs[formName].resetFields()
    },
    // 点击【新增】弹出新增界面方法
    addArea() {
      if (JSON.stringify(this.selOne) !== '{}') {
        const parentName = this.addRegionForm.name
        const parentId = this.addRegionForm.distinctId
        // eslint-disable-next-line no-unused-vars
        const parentCode = this.addRegionForm.code
        // this.oName = parentName
        // this.oCode = parentCode
        this.resetForm('addRegionForm')
        this.isAdd = true
        this.areaCodeShow = false
        this.addRegionForm = {
          parentName,
          parentId
        }
      } else {
        this.$message({
          message: '请先选择父级区域！',
          type: 'warning'
        })
      }
    },
    // 功能新增 【保存】方法
    sureAdd() {
      this.$refs.addRegionForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const para = Object.assign({}, this.addRegionForm)
          // 发送请求
          insertRegionInfo(para).then(res => {
            this.loading = false
            if (res.code === 0) {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.isAdd = false
              this.selOne = {}
              this.regionTreeInit(0)
            } else if (res.code === -1) {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }
          }).catch(err => {
            this.loading = false
            console.log(err)
          })
        }
      })
    },
    // 功能新增 【取消】
    closeAdd() {
      this.isAdd = false
      // this.addRegionForm = this.selOne
      if (this.oId !== '') {
        this.getRegDetail(this.oId)
      }
      // this.addRegionForm.name = this.oName
      // this.addRegionForm.code = this.oCode
      // this.selOne = {}
    },
    // 【删除】方法
    delArea() {
      if (JSON.stringify(this.selOne) !== '{}') {
        this.$confirm('该区域下可能存在子级,确定删除该区域？', '提示', {}).then(() => {
          this.loading = true
          delRegionById(this.selOne.distinctId).then(res => {
            this.loading = false
            if (res.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.selOne = {}
              this.regionTreeInit(0)
            } else if (res.code === -1) {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }
          }).catch(err => {
            this.loading = false
            console.log(err)
          })
        }).catch(() => {})
      } else {
        this.$message({
          message: '请选择要删除的区域！',
          type: 'error'
        })
      }
    }
  }
}
</script>
